import json

from PySide2.QtWidgets import QAction, QMenuBar


class FlowMenuBar(QMenuBar):
    def __init__(self, parent=None):
        super(FlowMenuBar, self).__init__(parent)
        with open("./doc/menu.json", "r", encoding="utf-8") as f:
            menu_json_array = json.load(f)
            self.set_menu(self,menu_json_array)

    def set_menu(self,menu:QMenuBar,items:dict):
        for menu_obj in items:
            type = menu_obj["type"]
            if type == "separator":
                menu.addSeparator()
                continue
            label = menu_obj["label"]
            if type =="command":
                function_name = menu_obj["function_name"]
                shortcut = menu_obj["shortcut"]
                # sub.triggered.connect(self.newFile)
                sub_action = QAction(label, self)
                sub_action.setShortcut(shortcut)
                sub_action.triggered.connect(open_file)
                menu.addAction(sub_action)
                continue
            if type == "menu":
                sub_items = menu_obj["items"]
                sub_menu = menu.addMenu(label)
                self.set_menu(sub_menu,sub_items)

